/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.extra.tags;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.gidoo.cms.GidooCMS;
import org.gidoo.cms.helper.Tools;
import org.gidoo.cms.jcr.JcrHelper;
import org.gidoo.cms.login.GidooCMSSession;

/**
 * A panel which lists all pages with a certain tag.
 *
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class TagListPanel extends Panel
{

  public TagListPanel(String id, String tagname)
  {
    super(id);

    final ArrayList<Entry> urls = new ArrayList<Entry>();
    try
    {

      QueryManager qm = ((GidooCMSSession) getSession()).getQueryManager();

      tagname = tagname.replaceAll("[ /]", "_");

      QueryResult r =
        qm.createQuery("/jcr:root/sections//cms:md/tags/" + tagname, Query.XPATH).execute();

      NodeIterator it = r.getNodes();
      while(it.hasNext())
      {
        Node n = it.nextNode();
        // get parent page node
        Node p = n.getParent().getParent().getParent();
        if(JcrHelper.isPublished(p))
        {
          String u = Tools.getRootURLForWebapp((GidooCMS) getApplication()) + JcrHelper.getPartialURLForNode(p);

          Entry e = new Entry();
          String t = "...";
          if(p.hasProperty("cms:title"))
          {
            t = p.getProperty("cms:title").getString();
          }
          e.url = u;
          e.title = t;
          Calendar c = Calendar.getInstance();
          if(p.hasProperty("cms:created"))
          {
            c = p.getProperty("cms:created").getDate();
          }
          e.created = c;
          urls.add(e);
        }
      }

    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(TagListPanel.class.getName()).log(Level.SEVERE, null, ex);
    }

    Collections.sort(urls, Collections.reverseOrder());

    ListView<Entry> lsvTag = new ListView<Entry>("lsvTag", urls)
    {

      @Override
      protected void populateItem(ListItem<Entry> item)
      {
        Entry e = urls.get(item.getIndex());
        AbstractLink lnkTag = new AbstractLink("lnkTag")
        {
        };
        lnkTag.add(new AttributeModifier("href", true,
          new Model(e.url)));

        item.add(lnkTag);

        String caption = e.title + " (" + e.url + ")";


        lnkTag.add(new Label("lblTag", new Model(caption)));
      }
    };

    add(lsvTag);
  }

  public class Entry implements Comparable<Entry>, Serializable
  {
    public String url;
    public String title;
    public Calendar created;

    public int compareTo(Entry o)
    {
      if(o != null)
      {
        return created.compareTo(o.created);
      }
      else
      {
        return -1;
      }
    }




  }

}
